package openglsuperbible.Chapter4;


import java.util.ArrayList;
import java.util.List;
import openglsuperbible.glutils.*;

import openglsuperbible.glutils.SimpleGLBatch;

import org.lwjgl.LWJGLException;
import org.lwjgl.Sys;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.*;
import static org.lwjgl.opengl.GL11.*;



public class SphereWorld2_1 {
        public static final int DISPLAY_HEIGHT = 600;
        public static final int DISPLAY_WIDTH = 800;
        private static final int MATRIX_SIZE = 16;
        
        private GLShader shader;        // Shader Manager
        private MatrixStack modelViewMatrix;  // Modelview Matrix
        private MatrixStack projectionMatrix; // Projection Matrix
        private GLFrustrum frustrum;    // View Frustum
        private GeometryTransform transformPipeline; // Geometry Transform Pipeline

        private GLBatch torusBatch;
        private GLBatch floorBatch;
        private GLBatch sphereBatch;

        
        
        float vFloorColor[] = { 0.0f, 1.0f, 0.0f, 1.0f};
        float vTorusColor[] = { 1.0f, 0.0f, 0.0f, 1.0f };
        float vSphereColor[] = { 0.0f, 0.0f, 1.0f, 1.0f };
        /** time at last frame */
	long lastFrame;
        
            public void initGL() {  
                shader = GLShaderFactory.getFlatShader();
                
                
                glEnable(GL_DEPTH_TEST);
                glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
                
                glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
                
                frustrum = new GLFrustrum();               
                modelViewMatrix = new MatrixStack();
                
                // This makes a torus
                torusBatch = GLBatchFactory.makeTorus(0.4f, 0.15f, 30, 30);
                sphereBatch = GLBatchFactory.makeSphere(0.1f, 26, 13);
                
                List<Float> floorvertlist = new ArrayList<Float>();
                float w = 1.0f;
                    for(float x = -20.0f; x <= 20.0f; x+= 0.5f) {

                            floorvertlist.add(x);
                            floorvertlist.add(-0.55f);
                            floorvertlist.add(20.0f);
                            floorvertlist.add(w);
                            
                            floorvertlist.add(x);
                            floorvertlist.add(-0.55f);
                            floorvertlist.add(-20.0f);
                            floorvertlist.add(w);
                            
                            floorvertlist.add(20.0f);
                            floorvertlist.add(-0.55f);
                            floorvertlist.add(x);
                            floorvertlist.add(w);
                            
                            floorvertlist.add(-20.0f);
                            floorvertlist.add(-0.55f);
                            floorvertlist.add(x);
                            floorvertlist.add(w);
                            
                }
                   
                    
                float[] floorverts = new float[floorvertlist.size()];
                
                for (int i = 0;i<floorvertlist.size();i++){
                        floorverts[i] = floorvertlist.get(i);
                }
                short[] floorindex = new short[floorvertlist.size()/4];
                for (int i =0; i < floorindex.length;i++)
                {
                    floorindex[i] =(short) i;
                    
                }
                
                floorBatch = new SimpleGLBatch(GL_LINES,floorverts,floorindex );                                 
                
            }   
  
            
            
            public void resizeGL() {   
                glViewport(0,0,DISPLAY_WIDTH ,DISPLAY_HEIGHT);
                frustrum.setPerspective(35.0f, Display.getWidth()/ Display.getHeight(),1.0f, 100.0f);
                projectionMatrix = new MatrixStack(frustrum.getProjectionMatrix());
                // Set the transformation pipeline to use the two matrix stacks 
	        transformPipeline = new GeometryTransform(modelViewMatrix, projectionMatrix);
            } 
          		
            
                        
            float angle = 0.0f;

            public void render() {
                angle+= 0.05f * getDelta();
                
                glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
                shader.useShader();                  
                // Save the current modelview matrix (the identity matrix)
                modelViewMatrix.push();
                shader.setUniform4("vColor",vFloorColor);                 
                shader.setUniformMatrix4("mvpMatrix", false, transformPipeline.getModelViewProjectionMatrix()); 
                floorBatch.draw(shader.getAttributeLocations());              
                           
                
                modelViewMatrix.translate(0, 0, -2.5f);

                
                modelViewMatrix.rotate(angle, 0.0f, 1.0f, 0.0f);  
                shader.setUniform4("vColor", vTorusColor);
                shader.setUniformMatrix4("mvpMatrix", false, transformPipeline.getModelViewProjectionMatrix());
                
                torusBatch.draw(shader.getAttributeLocations());
                
                // Apply another rotation, followed by a translation, then draw the sphere
                modelViewMatrix.rotate(angle * -2.0f, 0.0f, 1.0f, 0.0f); 
                modelViewMatrix.translate(0.8f, 0.0f, 0.0f);
                shader.setUniform4("vColor", vSphereColor);
                shader.setUniformMatrix4("mvpMatrix", false,  transformPipeline.getModelViewProjectionMatrix());
               
                sphereBatch.draw(shader.getAttributeLocations());
                
                // Restore the previous modleview matrix (the identity matrix)
                modelViewMatrix.pop();

                Display.update();  
            }  
            
        
        
       public void create() throws LWJGLException { 
            //Display    
            Display.setDisplayMode(new DisplayMode(DISPLAY_WIDTH,DISPLAY_HEIGHT)); 
            Display.setFullscreen(false);
            Display.setTitle("SphereWorld 2");
            Display.create(new PixelFormat(), new ContextAttribs(3, 2).withProfileCompatibility(true));
            //Keyboard         
            Keyboard.create();   
            //Mouse          
            Mouse.setGrabbed(false);
            Mouse.create();  
            //OpenGL      
            initGL();    
            resizeGL();  
        }  
       
       
       
            public void destroy() {  
                //Methods already check if created before destroying.  
                Mouse.destroy();   
                Keyboard.destroy();
                // Display.destroy();     
            } 
        
            public static void main(String[] args) {
            SphereWorld2_1 main = null;
            try { 
                 main = new SphereWorld2_1(); 
                main.create(); 
                main.run();
            }          
            catch(Exception ex) {  
                 
            }          
            finally { 
                if(main != null) {  
                    main.destroy();
                }         
            }      
        } 
            
            public void run() 
            {
                while (!Display.isCloseRequested() && !Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)) {              
                    if (Display.isVisible()) 
                    { 
                       
                        render();
                    }
                    else 
                    {     
                        if (Display.isDirty()) {
                           
                            render();
                        }
                    }          
            //Display.update();  
                  Display.sync(60);
                Display.setVSyncEnabled(true); 
                }                
                try{       
                    Thread.sleep(100); 
                } 
                catch (InterruptedException ex) {  }
             
            }
                        
                            	/** 
	 * Calculate how many milliseconds have passed 
	 * since last frame.
	 * 
	 * @return milliseconds passed since last frame 
	 */
	public int getDelta() {
	    long time = getTime();
	    int delta = (int) (time - lastFrame);
	    lastFrame = time;
	 
	    return delta;
	}
	
	/**
	 * Get the accurate system time
	 * 
	 * @return The system time in milliseconds
	 */
	public long getTime() {
	    return (Sys.getTime() * 1000) / Sys.getTimerResolution();
	}
}
